<template>
  <div
    v-if="isVisible"
    class="fixed right-0 top-0 bottom-0 w-96 bg-background border-l border-border shadow-lg z-50 flex flex-col transition-transform duration-300 ease-in-out"
    :class="{ 'translate-x-0': isVisible, 'translate-x-full': !isVisible }">
    <!-- 头部 -->
    <div class="flex items-center justify-between p-4 border-b border-border">
      <div class="flex items-center gap-2">
        <i class="i-mdi-robot text-primary h-5 w-5" />
        <h2 class="text-lg font-semibold text-foreground">{{ t('aiAssistant.title') }}</h2>
      </div>
      <button
        class="inline-flex items-center justify-center rounded-md p-1.5 transition-colors hover:bg-accent hover:text-accent-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
        :title="t('aiAssistant.closeTooltip')"
        @click="closeAssistant">
        <i class="i-mdi-close h-4 w-4" />
      </button>
    </div>

    <!-- 内容区域 -->
    <div class="flex-1 flex flex-col overflow-hidden">
      <!-- 聊天消息区域 -->
      <div class="flex-1 overflow-y-auto p-4 space-y-4">
        <!-- 欢迎消息 -->
        <div class="flex items-start gap-3">
          <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
            <i class="i-mdi-robot text-primary h-4 w-4" />
          </div>
          <div class="flex-1">
            <div class="bg-muted rounded-lg p-3">
              <p class="text-sm text-foreground">{{ t('aiAssistant.welcome') }}</p>
            </div>
          </div>
        </div>

        <!-- 消息列表 -->
        <div v-for="message in messages" :key="message.id" class="flex items-start gap-3">
          <div
            v-if="message.type === 'assistant'"
            class="flex-shrink-0 w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
            <i class="i-mdi-robot text-primary h-4 w-4" />
          </div>
          <div v-else class="flex-shrink-0 w-8 h-8 rounded-full bg-accent flex items-center justify-center">
            <i class="i-mdi-account text-accent-foreground h-4 w-4" />
          </div>

          <div class="flex-1">
            <div
              class="rounded-lg p-3"
              :class="message.type === 'assistant' ? 'bg-muted' : 'bg-primary text-primary-foreground'">
              <p class="text-sm" :class="message.type === 'assistant' ? 'text-foreground' : 'text-primary-foreground'">
                {{ message.content }}
              </p>
            </div>
            <div class="text-xs text-muted-foreground mt-1">
              {{ formatTime(message.timestamp) }}
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="isLoading" class="flex items-start gap-3">
          <div class="flex-shrink-0 w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center">
            <i class="i-mdi-robot text-primary h-4 w-4" />
          </div>
          <div class="flex-1">
            <div class="bg-muted rounded-lg p-3">
              <div class="flex items-center gap-2">
                <i class="i-mdi-loading animate-spin h-4 w-4" />
                <span class="text-sm text-muted-foreground">{{ t('aiAssistant.thinking') }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 输入区域 -->
      <div class="border-t border-border p-4">
        <div class="flex gap-2">
          <input
            v-model="inputMessage"
            type="text"
            :placeholder="t('aiAssistant.inputPlaceholder')"
            class="flex-1 px-3 py-2 text-sm bg-background border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2"
            @keydown.enter.exact="sendMessage"
            @keydown.ctrl.enter.exact="sendMessage" />
          <button
            class="inline-flex items-center justify-center rounded-md px-3 py-2 text-sm font-medium bg-primary text-primary-foreground transition-colors hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:opacity-50 disabled:pointer-events-none"
            :disabled="!inputMessage.trim() || isLoading"
            @click="sendMessage">
            <i class="i-mdi-send h-4 w-4" />
          </button>
        </div>
        <div class="text-xs text-muted-foreground mt-2">{{ t('aiAssistant.keyboardHint') }}</div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue';

import { t } from '@/i18n';
import { useAiAssistantStore } from '@/stores/aiAssistant';

interface Message {
  id: string;
  type: 'user' | 'assistant';
  content: string;
  timestamp: number;
}

const aiAssistantStore = useAiAssistantStore();

// 响应式数据
const inputMessage = ref('');
const messages = ref<Message[]>([]);
const isLoading = ref(false);

// 计算属性
const isVisible = computed(() => aiAssistantStore.isVisible);

// 方法
const closeAssistant = async () => {
  await aiAssistantStore.hideAssistant();
};

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

const generateId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

const sendMessage = async () => {
  const content = inputMessage.value.trim();
  if (!content || isLoading.value) return;

  // 添加用户消息
  const userMessage: Message = {
    id: generateId(),
    type: 'user',
    content,
    timestamp: Date.now()
  };
  messages.value.push(userMessage);

  // 清空输入
  inputMessage.value = '';

  // 设置加载状态
  isLoading.value = true;

  // 滚动到底部
  await nextTick();
  scrollToBottom();

  try {
    // 模拟AI响应（这里可以替换为实际的AI API调用）
    await new Promise((resolve) => setTimeout(resolve, 1000 + Math.random() * 2000));

    // 添加AI响应
    const assistantMessage: Message = {
      id: generateId(),
      type: 'assistant',
      content: generateAiResponse(),
      timestamp: Date.now()
    };
    messages.value.push(assistantMessage);
  } catch (error) {
    console.error('Failed to get AI response:', error);

    // 添加错误消息
    const errorMessage: Message = {
      id: generateId(),
      type: 'assistant',
      content: t('aiAssistant.errorResponse'),
      timestamp: Date.now()
    };
    messages.value.push(errorMessage);
  } finally {
    isLoading.value = false;

    // 滚动到底部
    await nextTick();
    scrollToBottom();
  }
};

const generateAiResponse = (): string => {
  // 简单的模拟AI响应逻辑
  const responses = [
    t('aiAssistant.responses.analysis'),
    t('aiAssistant.responses.suggestions'),
    t('aiAssistant.responses.information'),
    t('aiAssistant.responses.solutions'),
    t('aiAssistant.responses.considerations')
  ];

  return responses[Math.floor(Math.random() * responses.length)];
};

const scrollToBottom = () => {
  const container = document.querySelector('.overflow-y-auto');
  if (container) {
    container.scrollTop = container.scrollHeight;
  }
};
</script>

<style scoped>
/* 自定义滚动条 */
.overflow-y-auto::-webkit-scrollbar {
  width: 6px;
}

.overflow-y-auto::-webkit-scrollbar-track {
  background: transparent;
}

.overflow-y-auto::-webkit-scrollbar-thumb {
  background: hsl(var(--border));
  border-radius: 3px;
}

.overflow-y-auto::-webkit-scrollbar-thumb:hover {
  background: hsl(var(--muted-foreground));
}

/* 动画 */
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.animate-spin {
  animation: spin 1s linear infinite;
}
</style>
